﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using System.ServiceModel;
using System.ServiceModel.Activation;
using VAdvantage.DataBase;
using System.IO;
using System.Data;
using System.Net;
using VAdvantage.Model;
using System.Data.OracleClient;
using VAdvantage.Logging;
//using SilverlightFileUploadWeb;
using Google.GData.Client;
using Google.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.GData.YouTube;
using VAdvantageSvc.Classes;
using VAdvantageSvc.MarketService;
using VAdvantage.Utility;
using VAdvantage.Process;
using VAdvantage.ImpExp;
using System.Xml;
using System.Runtime.Serialization;

namespace VAdvantageSvc
{
    /******************************************** BASIC 2 ************************************/

    [ServiceContract(Namespace = "VAdvantageSvc")]
    public interface IDataServicesBasic2
    {
        [OperationContract]
        String GetDataXML(string sql, out CustomException ServiceError);

        [OperationContract]
        List<String> ExecuteMultipleQueries(List<String> sqlList, String trxName, out CustomException ServiceError);

        [OperationContract]
        List<int> ExecuteMultipleDeleteQueries(List<string> sqlList, string trxName, out CustomException error);

        [OperationContract]
        List<String> DeletePOCascade(int AD_Table_ID, int Record_ID, string trxName, out CustomException error);

        [OperationContract]
        AttachmentInfo GetAttachmentInfo(int AD_Attachment_ID, string tableName);
        [OperationContract]
        bool SetAttachmenInfo(AttachmentInfo aInfo, int AD_Attachment_ID, string tableName);
        [OperationContract]
        string SendSms(string url, List<String> mNumbers, List<String> mesages);
        [OperationContract]
        void UploadAttachment(AttachmentEntry attachment);
        [OperationContract]
        TenantInfo InitailizeClientSetup(ClientSetUp clientSetup, String fileName, IDictionary<string, string> ctxmap);
        //[OperationContract]
        //void InitializeLog(String clientName);
        [OperationContract]
        string SendMYEMail(String to, String from, String Subject, String msg, int smtpP, bool sl, string smtpH, string requestUser, string pws, IDictionary<string, string> ctxmap, int attchment_id);

        [OperationContract]
        String GetDataXMLPaging(string sql, int start, int pageSize, out CustomException ServiceError);

        [OperationContract]
        string SendMail(String to, string toName, String from, string fromName, String Subject, String msg, UserInformation user);

        [OperationContract]
        string SendMails(UserInformation user, List<NewMailMessage> mails, List<object> values, IDictionary<string, string> ctxmap);

        [OperationContract]
        string DeleteFiles();

        [OperationContract]
        ModelYTInfo GetStandardYouTubeFeed(string prmFeedIdentifier);
        // [OperationContract]
        //ModelYTInfo GetYouTubeByKeyword(string prmKeyword,
        //                                           Boolean prmSafeSearch,
        //                                           string prmOrderBy,
        //                                           string prmVideosBetweenTimeRange,
        //                                           string prmVideoCategory,
        //                                           int prmCurrentPage,
        //                                           int prmPageSize);
        [OperationContract]
        ModelYTInfo GetPrivateFeed(int sIndex, int pSize, string orderby
                                           , string lang, string search, string videoRange);



        //[OperationContract]
        //string GetConvertedCurrencyValue(CurrencyConverter.Currency from, CurrencyConverter.Currency to, string url);
        //[OperationContract]
        //string GetConvertedCurrencyValueM1(string from, string to, string url);

        [OperationContract]
        string SendWFSms(List<String> mNumbers, string mesages);
        [OperationContract]
        string SendWFEmail(String toEMail, String toName, String subject, String message, byte[] attachment, bool isHtml, IDictionary<string, string> ctxmap, int tableName, int recID);

        [OperationContract]
        string GetDataXmlFromExcel(AttachmentEntry attachment);

        [OperationContract]
        List<string> SendBulkMails(UserInformation user, List<NewMailMessage> mails, IDictionary<string, string> ctxmap);

        [OperationContract]
        bool SetProductQty(int recordID, string keyColName, List<int> product, List<decimal> qty, int lineID, IDictionary<string, string> ctxmap);
    }

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class DataServicesBasic2 : IDataServicesBasic2
    {
        private string connectionString = System.Configuration.ConfigurationSettings.AppSettings["oracleConnectionString"];

        /// <summary>
        /// Get Data xml String
        /// </summary>
        /// <param name="sql">sql in </param>
        /// <param name="error">out error</param>
        /// <returns>xml string</returns>
        public string GetDataXML(string sql, out CustomException error)
        {
            DataSet ds = null;
            try
            {
                ds = DB.ExecuteDataset(sql);// paramIn, trxName);
                //adapter.Fill(ds);//, 'Data');// (PageNumber - 1) * PageSize, PageSize, 'Data');
                //adapter.FillSchema(ds);//, SchemaType.Mapped, 'DataSchema');
                //if (PageSize > 0) // Reset Rowcount back to 0
                //{
                //    OracleCommand cmd = new OracleCommand('SET ROWCOUNT 0 SET NO_BROWSETABLE OFF', (OracleCommand)Connection);
                //    cmd.ExecuteNonQuery();
                //}
                if (ds.Tables.Count > 1)
                {
                    DataTable data = ds.Tables[0];
                    //DataTable schema = ds.Tables['DataSchema'];
                    // data.Merge(schema);
                    // ds.Tables.Remove(schema);
                }


                ds = Util.SetUtcDateTime(ds);

                //string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");
                error = null;
                // return schema + ds.GetXml() + " </TestDataSet>";

                StringWriter sw = new StringWriter();
                ds.WriteXml(sw, XmlWriteMode.WriteSchema);
                return sw.ToString();

            }
            catch (Exception err)
            {
                error = new CustomException(err);
            }
            return "";

        }

        /// <summary>
        /// Execute Multiplae Non queries(Only Select,Delete,Update)
        /// </summary>
        /// <param name="sqlList">list of sql</param>
        /// <param name="trxName">transaction name</param>
        /// <param name="error"></param>
        /// <returns>list of log(error only)</returns>
        public List<string> ExecuteMultipleQueries(List<string> sqlList, String trxName, out CustomException error)
        {
            List<String> logs = new List<string>();
            error = null;
            try
            {
                foreach (String sql in sqlList)
                {
                    try
                    {
                        DB.ExecuteQuery(sql, null, trxName);
                    }
                    catch
                    {
                        logs.Add(sql);
                    }
                }
            }
            catch (Exception e)
            {
                error = new CustomException(e);
            }
            return logs;
        }

        /// <summary>
        /// Multiple delete 
        /// </summary>
        /// <param name="sqlList">list of sql </param>
        /// <param name="trxName">transaction</param>
        /// <param name="error"></param>
        /// <returns>lsit of int [ less tham zero =>error else >=0 =>success</returns>
        public List<int> ExecuteMultipleDeleteQueries(List<string> sqlList, string trxName, out CustomException error)
        {
            List<int> logs = new List<int>();
            error = null;
            try
            {
                foreach (String sql in sqlList)
                {
                    int no = DB.ExecuteQuery(sql.ToString(), null, trxName);
                    logs.Add(no);
                }
            }
            catch (Exception e)
            {
                error = new CustomException(e);
            }
            return logs;
        }

        #region IDataServicesBasic2 Members

        /// <summary>
        /// delete PO dependent record (Only for AD_part)
        /// </summary>
        /// <param name="AD_Table_ID"></param>
        /// <param name="Record_ID"></param>
        /// <param name="trxName"></param>
        /// <param name="error"></param>
        /// <returns>list of log</returns>
        public List<string> DeletePOCascade(int AD_Table_ID, int Record_ID, string trxName, out CustomException error)
        {
            error = null;
            return VAdvantage.Model.PORecord.DeletePOCascade(AD_Table_ID, Record_ID, trxName);
        }

        #endregion

        /// <summary>
        /// Load Attachment of Record
        /// </summary>
        /// <param name="AD_Attachment_ID">key</param>
        /// <param name="tableName">tablename</param>
        /// <returns></returns>
        public AttachmentInfo GetAttachmentInfo(int AD_Attachment_ID, string tableName)
        {
            try
            {
                AttachmentInfo ainfo = new AttachmentInfo();
                if (tableName.Equals("AD_ATTACHMENT", StringComparison.OrdinalIgnoreCase))
                {
                    VAdvantage.Model.MAttachment mattach = new VAdvantage.Model.MAttachment(VAdvantage.Utility.Env.GetCtx(), AD_Attachment_ID, null);
                    ainfo.AttachmentEntries = new List<AttachmentEntry>();

                    for (int i = 0; i < mattach.GetEntryCount(); i++)
                    {
                        ainfo.TextMessage = mattach.GetTextMsg();
                        ainfo.AttachmentEntries.Add(new AttachmentEntry(mattach.GetEntry(i).GetName(), mattach.GetEntry(i).GetData(), i));
                    }
                }
                else
                {
                    VAdvantage.Model.MMailAttachment1 mailAttach = new VAdvantage.Model.MMailAttachment1(VAdvantage.Utility.Env.GetCtx(), AD_Attachment_ID, null);
                    ainfo.AttachmentEntries = new List<AttachmentEntry>();
                    for (int i = 0; i < mailAttach.GetEntryCount(); i++)
                    {
                        // AttachmentInfo s = new AttachmentInfo();

                        ainfo.TextMessage = mailAttach.GetTextMsg();
                        ainfo.AttachmentEntries.Add(new AttachmentEntry(mailAttach.GetEntry(i).GetName(), mailAttach.GetEntry(i).GetData(), i));

                    }
                }
                return ainfo;
            }
            catch
            {
                return null;
            }

            finally
            {
                //Connection.Close();
            }
        }

        /// <summary>
        /// Save Attachments of Record
        /// </summary>
        /// <param name="aInfo">dataContract</param>
        /// <param name="AD_Attachment_ID">key </param>
        /// <param name="tableName">tabl name</param>
        /// <returns></returns>
        public bool SetAttachmenInfo(AttachmentInfo aInfo, int AD_Attachment_ID, string tableName)
        {
            if (aInfo == null)
            {
                return false;
            }
            bool result = false;

            if (tableName.Equals("AD_ATTACHMENT", StringComparison.OrdinalIgnoreCase))
            {
                MAttachment attch = new MAttachment(VAdvantage.Utility.Env.GetCtx(), AD_Attachment_ID, null);
                attch.InitEntries(); //Clear Entries

                List<KeyValuePair<String, byte[]>> lst = new List<KeyValuePair<string, byte[]>>();
                KeyValuePair<string, byte[]> keyVal;

                int isize = aInfo.AttachmentEntries.Count;
                for (int i = 0; i < isize; i++)
                {
                    AttachmentEntry item = aInfo.AttachmentEntries[i];
                    attch.AddEntry(item.Name, item.Data);
                    //AttachmentEntry item = aInfo.AttachmentEntries[i];
                    //keyVal = new KeyValuePair<string, byte[]>(item.Name, item.Data);
                    //lst.Add(keyVal);
                }
                result = attch.Save();
            }
            else
            {
                MMailAttachment1 mattch = new MMailAttachment1(VAdvantage.Utility.Env.GetCtx(), AD_Attachment_ID, null);
                mattch.InitEntries(); //Clear Entries

                List<KeyValuePair<String, byte[]>> lst = new List<KeyValuePair<string, byte[]>>();
                KeyValuePair<string, byte[]> keyVal;

                int isize = aInfo.AttachmentEntries.Count;
                for (int i = 0; i < isize; i++)
                {
                    AttachmentEntry item = aInfo.AttachmentEntries[i];
                    mattch.AddEntry(item.Name, item.Data);
                }
                result = mattch.Save();
            }
            return result;

        }

        public void UploadAttachment(AttachmentEntry attachment)
        {

            string name = attachment.Name;
            byte[] data = attachment.Data;
            string storedAttachmentPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, name);
            if (!System.IO.File.Exists(storedAttachmentPath))
            {
                FileStream fs = new FileStream(storedAttachmentPath, FileMode.CreateNew);
                fs.Write(data, 0, data.Length);
                fs.Flush();
                fs.Close();
            }


        }

        public string GetDataXmlFromExcel(AttachmentEntry attachment)
        {
            string name = attachment.Name;
            byte[] data = attachment.Data;
            string storedAttachmentPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, name);
            if (!System.IO.File.Exists(storedAttachmentPath))
            {
                FileStream fs = new FileStream(storedAttachmentPath, FileMode.CreateNew);
                fs.Write(data, 0, data.Length);
                fs.Flush();
                fs.Close();
            }
            ExcelReader reader = new ExcelReader(1, 1);
            System.Data.DataTable dt = reader.ExtractDataTable(storedAttachmentPath, "Sheet1$");    //extract all the records form excel to DataTable

            StringBuilder sb = new StringBuilder();
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");

            return schema + ds.GetXml() + " </TestDataSet>";
            //sb.Append("<?xml version='1.0' encoding='utf-8' ?>");
            //sb.Append("<DocumentElement>");

            //foreach (DataRow dr in dt.Rows)
            //{
            //    sb.Append("<" + dt.TableName + ">");

            //    foreach (DataColumn dc in dt.Columns)
            //        sb.Append("<" + dc.ColumnName + ">" +
            //                dr[dc].ToString() +
            //             "</" + dc.ColumnName + ">");

            //    sb.Append("</" + dt.TableName + ">");
            //}

            //sb.Append("</DocumentElement>");


            //return sb.ToString();




        }


        public TenantInfo InitailizeClientSetup(ClientSetUp clientSetup, String fileName, IDictionary<string, string> ctxmap)
        {
            VAdvantage.Classes.Context ctx = new VAdvantage.Classes.Context(ctxmap);
            TenantInfo tInfo = new TenantInfo();


            try
            {
                tInfo.TenantName = clientSetup.FClientName;

                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = "AccountingUS1.csv";
                }
                string retVal = "";
                FileStream m_file = new FileStream(HostingEnvironment.ApplicationPhysicalPath + fileName, FileMode.Open);
                // worker.ReportProgress(0);
                MSetup ms = new MSetup(ctx, 0);
                //  Step 1
                //bool ok = ms.CreateClient(fClientName.Text, fOrgName.Text, fUserClient.Text, fUserOrg.Text);
                bool ok = false;
                TenantInfoM clientInfo = ms.CreateClient(clientSetup.FClientName, clientSetup.FOrgName, clientSetup.FUserClient, clientSetup.FUserOrg);
                if (string.IsNullOrEmpty(clientInfo.Log))
                {
                    ok = true;
                }
                tInfo.TenantName = clientInfo.TenantName;
                tInfo.OrgName = clientInfo.OrgName;
                tInfo.AdminRole = clientInfo.AdminRole;
                tInfo.UserRole = clientInfo.UserRole;
                tInfo.AdminUser = clientInfo.AdminUser;
                tInfo.AdminUserPwd = clientInfo.AdminUserPwd;
                tInfo.OrgUser = clientInfo.OrgUser;
                tInfo.OrgUserPwd = clientInfo.OrgUserPwd;
                // worker.ReportProgress(10);
                String info = ms.GetInfo();

                if (ok)
                {
                    //  Generate Accounting
                    // worker.ReportProgress(15);
                    // if (!ms.CreateAccounting(currency, cfProduct, cfBPartner, cfProject, cfMCampaign, cfSRegion, m_file))
                    // KeyNamePair currency = new KeyNamePair(clientSetup.currency.Key, clientSetup.currency.Value);
                    KeyNamePair currency = new KeyNamePair(clientSetup.currency.key, clientSetup.currency.value);
                    if (!ms.CreateAccounting(currency, clientSetup.cfProduct, clientSetup.cfBPartner, clientSetup.cfProject, clientSetup.cfMCampaign, clientSetup.cfSRegion, m_file))
                    {
                        //ShowMessage.Error("AccountSetupError", false);
                        //Dispose();
                        retVal = "AccountSetupError";
                        tInfo.Log = retVal;
                    }
                    // worker.ReportProgress(45);
                    //  Generate Entities

                    int C_Country_ID = clientSetup.pCurrency.key;

                    int C_Region_ID = clientSetup.pRegion.key;
                    //  worker.ReportProgress(75);
                    ms.CreateEntities(C_Country_ID, clientSetup.FCity, C_Region_ID, clientSetup.currency.key);
                    //worker.ReportProgress(90);
                    info += ms.GetInfo();
                    //	Create Print Documents
                    ms.SetupPrintForm(ms.GetAD_Client_ID());
                    // worker.ReportProgress(100);
                }

                //try
                //{
                //    System.IO.File.Delete(HostingEnvironment.ApplicationPhysicalPath + fileName);
                //}
                //catch (Exception ex)
                //{
                //    retVal += (ex.Message);
                //}


                tInfo.Log = retVal;
                try
                {
                    if (m_file != null)
                        m_file.Close();
                }
                catch { }
            }
            catch (Exception ex)
            {
                tInfo.Log = ex.Message;

            }

            return tInfo;// retVal;


        }

        public string SendSms(string url, List<String> mbNumbers, List<String> msgs)
        {

            string mbNumber = "";
            string msg = "";
            StringBuilder result = new StringBuilder("");

            IDataReader idr = null;
            idr = VAdvantage.DataBase.DB.ExecuteReader("select * from ad_smsconfiguration WHERE isactive='Y'");
            DataTable dt = new DataTable();
            dt.Load(idr);
            idr.Close();
            if (dt.Rows.Count == 0)
            {
                return "SmsConfigurationNotFound";
            }


            string strUrl = dt.Rows[0]["url"].ToString() + "?" + dt.Rows[0]["userKeyword"].ToString() + "=" +
                     dt.Rows[0]["username"].ToString() + "&" + dt.Rows[0]["PasswordKeyword"].ToString() + "=" +
                     dt.Rows[0]["password"].ToString() + "&" +
                     dt.Rows[0]["senderKeyword"].ToString() + "=" + dt.Rows[0]["sender"].ToString() + "&" +
                     dt.Rows[0]["messageKeyword"].ToString() + "=" +
                     "@@Messag@@" + "&" + dt.Rows[0]["MobilenumberKeyword"].ToString() + "=" + "@@Mobile@@" + "&";
            strUrl += dt.Rows[0]["priorityKeyword"].ToString() + "=" + dt.Rows[0]["priorityValue"].ToString();
            if (dt.Rows[0]["unicodeValue"].ToString().Length > 0 || dt.Rows[0]["dndValue"].ToString().Length > 0)
            {
                strUrl += "&" + dt.Rows[0]["dndKeyword"].ToString() + "=" + dt.Rows[0]["dndValue"].ToString() +
                    "&" + dt.Rows[0]["unicodeKeyword"].ToString() + "=" + dt.Rows[0]["unicodeValue"].ToString();
            }


            String resultmsg = "";
            for (int i = 0; i < mbNumbers.Count; i++)
            {
                mbNumber = mbNumbers[i];
                msg = msgs[i];
                string[] subNumberList = mbNumber.Split(';');
                try
                {

                    for (int j = 0; j < subNumberList.Length; j++)
                    {

                        string strRep = Replace(msg);
                        string repMob = Replace(subNumberList[j]);
                        string uri = strUrl.Replace("@@Messag@@", strRep);
                        uri = uri.Replace("@@Mobile@@", repMob);
                        // uri += mbNumber;

                        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(uri);
                        HttpWebResponse resp = (HttpWebResponse)webReq.GetResponse();//send sms
                        StreamReader responseReader = new StreamReader(resp.GetResponseStream());//read the response 
                        resultmsg += responseReader.ReadToEnd();//get result
                        responseReader.Close();
                        resp.Close();

                    }
                    result.Append(resultmsg).Append(",");
                    resultmsg = "";
                }
                catch (Exception e)
                {
                    result.Append(mbNumber).Append("-").Append(e.Message).Append(",");
                }
            }
            return result.ToString();
        }

        public string SendWFSms(List<String> mNumbers, string mesages)
        {
            IDataReader idr = null;
            idr = VAdvantage.DataBase.DB.ExecuteReader("select * from ad_smsconfiguration WHERE isactive='Y'");
            DataTable dt = new DataTable();
            dt.Load(idr);
            idr.Close();
            if (dt.Rows.Count == 0)
            {
                return "SmsConfigurationNotFound";
            }


            string strUrl = dt.Rows[0]["url"].ToString() + "?" + dt.Rows[0]["userKeyword"].ToString() + "=" +
                     dt.Rows[0]["username"].ToString() + "&" + dt.Rows[0]["PasswordKeyword"].ToString() + "=" +
                     dt.Rows[0]["password"].ToString() + "&" +
                     dt.Rows[0]["senderKeyword"].ToString() + "=" + dt.Rows[0]["sender"].ToString() + "&" +
                     dt.Rows[0]["messageKeyword"].ToString() + "=" +
                     "@@Messag@@" + "&" + dt.Rows[0]["MobilenumberKeyword"].ToString() + "=" + "@@Mobile@@" + "&";
            strUrl += dt.Rows[0]["priorityKeyword"].ToString() + "=" + dt.Rows[0]["priorityValue"].ToString();
            if (dt.Rows[0]["unicodeValue"].ToString().Length > 0 || dt.Rows[0]["dndValue"].ToString().Length > 0)
            {
                strUrl += "&" + dt.Rows[0]["dndKeyword"].ToString() + "=" + dt.Rows[0]["dndValue"].ToString() +
                    "&" + dt.Rows[0]["unicodeKeyword"].ToString() + "=" + dt.Rows[0]["unicodeValue"].ToString();
            }

            String resultmsg = "";
            for (int i = 0; i < mNumbers.Count; i++)
            {
                string uri = strUrl.Replace("@@Messag@@", mesages);
                uri = uri.Replace("@@Mobile@@", mNumbers[i]);
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(uri);
                HttpWebResponse resp = (HttpWebResponse)webReq.GetResponse();//send sms
                StreamReader responseReader = new StreamReader(resp.GetResponseStream());//read the response 
                resultmsg += mNumbers[i] + "->" + responseReader.ReadToEnd();//get result
                responseReader.Close();
                resp.Close();
            }
            return resultmsg;
        }

        public string SendWFEmail(String toEMail, String toName, String subject, String message, byte[] attachment, bool isHtml, IDictionary<string, string> ctxmap, int tableID, int recID)
        {
            VAdvantage.Classes.Context ctx = new VAdvantage.Classes.Context(ctxmap);
            MClient client = new MClient(ctx, ctx.GetAD_Client_ID(), null);

            MTable table = new MTable(ctx, tableID, null);
            PO _po = table.GetPO(ctx, recID, null);
            DocAction doc = (DocAction)_po;
            FileInfo pdf = doc.CreatePDF();

            MOrder order = new MOrder(ctx, 0, null);



            EMail email = client.CreateEMail(toEMail, toName, subject, message, isHtml);
            if (email == null)
                return null;
            if (pdf != null)
            {

                email.AddAttachment(pdf);

            }
            try
            {
                return email.Send();
                //if (EMail.SENT_OK.Equals(msg))
                //{
                //    //log.info("Sent EMail " + subject + " to " + toEMail);
                //    return true;
                //}
                //else
                //{
                //    //log.warning("Could NOT Send Email: " + subject + " to " + toEMail + ": " + msg + " (" + GetName() + ")");
                //    return false;
                //}
            }
            catch (Exception ex)
            {
                //log.severe(GetName() + " - " + ex.Message);
                return ex.Message;
            }
        }


        private string Replace(string str)
        {
            StringBuilder replaceSpecilChar = new StringBuilder();
            replaceSpecilChar.Append(str);
            // replaceSpecilChar.Replace("%", "%25");
            replaceSpecilChar.Replace("#", "%23");
            replaceSpecilChar.Replace("$", "%24");
            replaceSpecilChar.Replace("&", "%26");
            replaceSpecilChar.Replace("+", "%2B");
            replaceSpecilChar.Replace(",", "%2C");
            replaceSpecilChar.Replace(":", "%3A");
            replaceSpecilChar.Replace(";", "%3B");
            replaceSpecilChar.Replace("=", "%3D");
            replaceSpecilChar.Replace("?", "%3F");
            replaceSpecilChar.Replace("@", "%40");
            replaceSpecilChar.Replace("<", "%3C");
            replaceSpecilChar.Replace(">", "%3E");
            replaceSpecilChar.Replace("{", "%7B");
            replaceSpecilChar.Replace("}", "%7D");
            replaceSpecilChar.Replace("|", "%7C");
            replaceSpecilChar.Replace("\\", "%5C");
            replaceSpecilChar.Replace("^", "%5E");
            replaceSpecilChar.Replace("~", "%7E");
            replaceSpecilChar.Replace("[", "%5B");
            replaceSpecilChar.Replace("]", "%5D");
            replaceSpecilChar.Replace("`", "%60");

            return replaceSpecilChar.ToString();
        }

        //public void InitializeLog(String clientName)
        //{
        //    //string logStatus = System.Configuration.ConfigurationSettings.AppSettings["log"];
        //    string logStatus = System.Configuration.ConfigurationManager.AppSettings["TraceLog"];
        //    string traceLevel = System.Configuration.ConfigurationManager.AppSettings["TraceLevel"];
        //    if (logStatus == "Y")
        //    {
        //        string storedPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "");
        //        storedPath += clientName;
        //        VLogMgt.Initialize(true, storedPath);
        //       // VLogMgt.AddHandler(VLogFile.Get(true, Ini.FindHome(), true));
        //       // VLogMgt.AddHandler(VLogFile.Get(true, storedPath, true));
        //        LogManager log = new LogManager();
        //        log.Reset();
        //    }
        //}


        /// <summary>
        /// To Send Mail
        /// </summary>
        /// <returns>OK or error message</returns>
        public string SendMYEMail(String to, String from, String Subject, String msg, int smtpP, bool sl, string smtpH, string requestUser, string pws, IDictionary<string, string> ctxmap, int attchment_id)
        {

            VAdvantage.Classes.Context ctx = new VAdvantage.Classes.Context(ctxmap);
            if (ctx == null)
            {
                return "";
            }
            int smtpPort = smtpP;
            string smtpHost = smtpH;
            bool ssl = sl;

            VAdvantage.Utility.EMail email = new VAdvantage.Utility.EMail(ctx, smtpHost, smtpPort, ssl, from, "", to, "", Subject, msg);
            email.CreateAuthenticator(requestUser, pws);
            MAttachment attachment = new MAttachment(ctx, attchment_id, null);
            for (int i = 0; i < attachment.GetEntryCount(); i++)
            {
                email.AddAttachment(attachment.GetEntry(i).GetData(), attachment.GetEntry(i).GetName());
            }
            return email.Send();
        }

        public string SendMail(String to, string toName, String from, string fromName, String Subject, String msg, UserInformation user)
        {
                try
                {
                    StringBuilder log = new StringBuilder();
                    int smtpPort = user.HostPort;
                    string smtpHost = user.Host;
                    bool ssl = user.UseSSL;
                    string clientName = "MailServerLog";
                    string storedPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, clientName);
                    VLogMgt.Initialize(true, storedPath);
                    VLogger.Get().Info("port : " + smtpPort);
                    VLogger.Get().Info("host : " + smtpHost);
                    VLogger.Get().Info("Userame : " + user.Username);
                    VLogger.Get().Info("password : " + user.Password);
                    log.Append("port : " + smtpPort);
                    log.Append("host : " + smtpHost);
                    log.Append("Userame : " + user.Username + ", password : " + user.Password);
                    VAdvantage.MailBox.SMTPConfig smtp = new VAdvantage.MailBox.SMTPConfig();
                    smtp.Host = user.Host;
                    smtp.Password = user.Password;
                    //smtp.ServerPort=user.HostPort;
                    smtp.SmtpAuthentication = user.SmtpAuthentication;
                    smtp.UserName = user.Username;
                    smtp.UseSSL = user.UseSSL;
                    // VAdvantage.Utility.EMail email = new VAdvantage.Utility.EMail(null, smtpHost, smtpPort, ssl, from, fromName, to, toName, Subject, msg);
                    VAdvantage.Utility.EMail email = new VAdvantage.Utility.EMail(null, smtp, from, fromName, to, toName, Subject, msg, false);

                    File.AppendAllText(HostingEnvironment.ApplicationPhysicalPath + "\\log\\MailLog.txt", log.ToString());
                    return email.Send();

                }
                catch (Exception ex)
                {
                    VLogger.Get().Info("Mail Not Sent : " + ex.Message);
                    return "Mail Not Sent : " + ex.Message;
                }
        }


        public String GetDataXMLPaging(string sql, int start, int pageSize, out CustomException ServiceError)
        {

            DataSet ds = null; ;
            OracleConnection Connection = new OracleConnection(System.Configuration.ConfigurationSettings.AppSettings["oracleConnectionString"]);
            ServiceError = null;
            try
            {
                // Ctx ctx = new Ctx(ctxDic);
                //string clientName = "Log";
                //string storedPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "");
                //storedPath += clientName;

                OracleDataAdapter adapter = new OracleDataAdapter();

                adapter.SelectCommand = new OracleCommand(sql);
                Connection.Open();

                adapter.SelectCommand.Connection = Connection;
                //if (PageSize > 0)// Set rowcount =PageNumber * PageSize for best performance
                //{
                //    long RowCount = PageNumber * PageSize;
                //    OracleCommand cmd = new OracleCommand('SET ROWCOUNT ' + RowCount.ToString() + ' SET NO_BROWSETABLE ON', (OracleConnection)Connection);
                //    cmd.ExecuteNonQuery();
                //}
                ds = new DataSet();
                adapter.Fill(ds, start, pageSize, "Table");
                //adapter.FillSchema(ds);//, SchemaType.Mapped, 'DataSchema');
                //if (PageSize > 0) // Reset Rowcount back to 0
                //{
                //    OracleCommand cmd = new OracleCommand('SET ROWCOUNT 0 SET NO_BROWSETABLE OFF', (OracleCommand)Connection);
                //    cmd.ExecuteNonQuery();
                //}
                if (ds.Tables.Count > 1)
                {
                    DataTable data = ds.Tables[0];
                    //DataTable schema = ds.Tables['DataSchema'];
                    // data.Merge(schema);
                    // ds.Tables.Remove(schema);
                }
            }
            catch (Exception err)
            {
                ServiceError = new CustomException(err);
                return "";
            }
            finally
            {
                Connection.Close();
            }

            ds = Util.SetUtcDateTime(ds);

            //string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");
            // error = null;

            // return schema + ds.GetXml() + " </TestDataSet>";

            StringWriter sw = new StringWriter();
            ds.WriteXml(sw, XmlWriteMode.WriteSchema);
            return sw.ToString();


            // return "tested";

            //  return ds.GetXml();
        }

        static string  AttachmentsUploadFolderName = "UploadedAttachments";

        private readonly string attachmentsDirectory = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, AttachmentsUploadFolderName);
        bool chk = false;
        public string SendMails(UserInformation user, List<NewMailMessage> mails, List<object> values, IDictionary<string, string> ctxmap)
        {
            VAdvantage.Classes.Context ctx = new VAdvantage.Classes.Context(ctxmap);
            if (ctx == null)
            {
                return null;
            }

            string smtphost = user.Host;
            int smtpport = user.HostPort;
            bool issl = user.UseSSL;
            //string sql = values[0].ToString();
            //string from = VAdvantage.DataBase.DB.ExecuteScalar(sql).ToString();

            string from = user.Email;

            string[] to = null;
            string[] bc = null;
            StringBuilder bcctext = new StringBuilder();
            StringBuilder totext = new StringBuilder();
            StringBuilder cctext = new StringBuilder();
            string[] cc = null;
            string sub = null;
            string message = null;
            int _record_id = 0;
            int _table_id = 0;

            string[] records = null;





            StringBuilder res = new StringBuilder();


            List<NewMailMessage> mail = mails.GetRange(0, mails.Count);
            if (mails.Count == 1 && mails[0].From != null)          //in case of static mail
            {
                records = mails[0].From.Split(',');

            }
            for (int j = 0; j < mails.Count; j++)
            {
                to = mails[j].To;
                bc = mails[j].Bcc;
                cc = mails[j].Cc;
                //sub = mails[i].Subject;
                //message = mails[i].Body; 

                sub = mails[j].Subject;
                message = mails[j].Body;
                //  _record_id = Convert.ToInt32(mails[j].From);
                if (records != null && records.Length > 1)  //if static mail
                {
                    _record_id = Convert.ToInt32(records[j]);
                }
                else
                {
                    if (mails[j].From != null)
                    {
                        _record_id = Convert.ToInt32(mails[j].From);//if dynamic mail
                    }
                    else
                    {
                        _record_id = -1;// in case of window having no Email feild...
                    }
                }
                _table_id = Convert.ToInt32(mail[j].Sender);

                VAdvantage.Model.MMailAttachment1 _mAttachment = new VAdvantage.Model.MMailAttachment1(ctx, 0, null);

                //VAdvantage.Utility.EMail sendmail = new VAdvantage.Utility.EMail(ctx, smtphost, smtpport, issl, from, "", "", "", sub, message, true);
                //if (user.SmtpAuthentication)
                //{
                //    sendmail.CreateAuthenticator(user.Username, user.Password);
                //}

                VAdvantage.Utility.EMail sendmail = new VAdvantage.Utility.EMail(ctx, smtphost, smtpport, issl, from, "", "", "", sub, message,
                    true, user.Username, user.Password, user.SmtpAuthentication);


                foreach (var newAttachment in mails[j].Attachments)
                {
                    // open file

                    string storedAttachmentPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, AttachmentsUploadFolderName, newAttachment.StoredFileName);
                    FileStream attachmentStream = File.OpenRead(storedAttachmentPath);
                    BinaryReader binary = new BinaryReader(attachmentStream);
                    byte[] buffer = binary.ReadBytes((int)attachmentStream.Length);
                    sendmail.AddAttachment(buffer, newAttachment.FileName);
                    _mAttachment.AddEntry(newAttachment.FileName, buffer);
                    attachmentStream.Flush();
                    attachmentStream.Close();
                }

                if (to != null)
                {

                    for (int i = 0; i < to.Length; i++)
                    {
                        if (to[i].ToString() != "")
                        {
                            sendmail.AddTo(to[i].ToString(), "");
                            totext.Append(to[i].ToString() + ",");
                        }
                    }
                }

                if (bc != null)
                {
                    for (int i = 0; i < bc.Length; i++)
                    {
                        if (bc[i].ToString() != "")
                        {
                            sendmail.AddBcc(bc[i].ToString(), "");
                            bcctext.Append(bc[i].ToString() + ",");
                        }
                    }
                }

                if (cc != null)
                {
                    for (int i = 0; i < cc.Length; i++)
                    {
                        if (cc[i].ToString() != "")
                        {
                            sendmail.AddCc(cc[i].ToString(), "");
                            cctext.Append(cc[i].ToString() + ",");
                        }
                    }
                }

                string res1 = sendmail.Send();

                if (records != null && records.Length > 1)//to save entry in mAttachment in static mail....
                {
                    for (int k = 0; k < records.Length - 1; k++)
                    {
                        if (res1 != "OK")
                        {
                            _mAttachment.SetIsMailSent(false);
                        }
                        else
                        {
                            _mAttachment.SetIsMailSent(true);
                        }
                        int AD_Client_Id = ctx.GetAD_Client_ID();
                        int iOrgid = ctx.GetAD_Org_ID();

                        _mAttachment.SetAD_Client_ID(AD_Client_Id);
                        _mAttachment.SetAD_Org_ID(iOrgid);
                        _mAttachment.SetAD_Table_ID(_table_id);
                        _mAttachment.IsActive();
                        _mAttachment.SetMailAddress(bcctext.ToString());
                        _mAttachment.SetAttachmentType("M");

                        _mAttachment.SetRecord_ID(Convert.ToInt32(records[k]));

                        _mAttachment.SetTextMsg(message);
                        _mAttachment.SetTitle(sub);

                        _mAttachment.SetMailAddressBcc(bcctext.ToString());
                        _mAttachment.SetMailAddress(totext.ToString());
                        _mAttachment.SetMailAddressCc(cctext.ToString());
                        _mAttachment.SetMailAddressFrom(from);
                        if (_mAttachment.GetEntries().Length > 0)
                        {
                            _mAttachment.SetIsAttachment(true);
                        }
                        else
                        {
                            _mAttachment.SetIsAttachment(false);
                        }
                        _mAttachment.NewRecord();
                        if (_mAttachment.Save())
                        { }
                        else
                        {
                            // log.SaveError(Msg.GetMsg(Env.GetCtx(), "RecordNotSaved"), "");
                        }
                    }
                }
                else//To save entry in MAttachment in case of Dynamic mail...
                {

                    if (res1 != "OK")
                    {
                        _mAttachment.SetIsMailSent(false);
                    }
                    else
                    {
                        _mAttachment.SetIsMailSent(true);
                    }

                    int AD_Client_Id = ctx.GetAD_Client_ID();
                    int iOrgid = ctx.GetAD_Org_ID();
                    //MTable table = MTable.Get(ctx, 0);//fixed table for MailAttachment1
                    _mAttachment.SetAD_Client_ID(AD_Client_Id);
                    _mAttachment.SetAD_Org_ID(iOrgid);
                    _mAttachment.SetAD_Table_ID(_table_id);
                    _mAttachment.IsActive();
                    _mAttachment.SetMailAddress(bcctext.ToString());
                    _mAttachment.SetAttachmentType("M");

                    _mAttachment.SetRecord_ID(_record_id);

                    _mAttachment.SetTextMsg(message);
                    _mAttachment.SetTitle(sub);

                    _mAttachment.SetMailAddressBcc(bcctext.ToString());
                    _mAttachment.SetMailAddress(totext.ToString());
                    _mAttachment.SetMailAddressCc(cctext.ToString());
                    _mAttachment.SetMailAddressFrom(from);
                    if (_mAttachment.GetEntries().Length > 0)
                    {
                        _mAttachment.SetIsAttachment(true);
                    }
                    else
                    {
                        _mAttachment.SetIsAttachment(false);
                    }
                    _mAttachment.NewRecord();
                    if (_mAttachment.Save())
                    { }
                    else
                    {
                        // log.SaveError(Msg.GetMsg(Env.GetCtx(), "RecordNotSaved"), "");
                    }
                }

                if (res1 != "OK")
                {
                    if (res1 == "AuthenticationFailed.")
                    {
                        res.Append(res1);
                        return res.ToString();
                    }
                    else
                    {
                        res.Append("Mailnotsentto" + ": " + totext + " " + bcctext + " " + cctext);
                    }


                }
                else
                {
                    // if (!chk)
                    {
                        if (!res.ToString().Contains("MailSent"))
                        {
                            res.Append("MailSent");
                            chk = true;
                        }
                    }
                    //  _mAttachment.SetIsMailSent(true);

                }

            }

            try
            {
                if (Directory.Exists(this.attachmentsDirectory))
                {
                    foreach (var file in Directory.GetFiles(this.attachmentsDirectory))
                    {
                        var creationTime = File.GetCreationTime(file);
                        if (DateTime.Now - creationTime > TimeSpan.FromHours(1))
                        {
                            File.Delete(file);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                res.Append(ex.Message);
            }

            //}
            user = null;
            mail = null;
            values = null;
            ctxmap = null;
            ctx = null;
            smtphost = null;
            smtpport = 0;
            issl = false;
            cc = null;
            bc = null; bcctext = null;
            to = null; records = null;
            sub = null; message = null;
            from = null;
            records = null;

            return res.ToString();
        }

        public List<string> SendBulkMails(UserInformation user, List<NewMailMessage> mails, IDictionary<string, string> ctxmap)
        {
            VAdvantage.Classes.Context ctx = new VAdvantage.Classes.Context(ctxmap);
            string smtphost = user.Host;
            int smtpport = user.HostPort;
            bool issl = user.UseSSL;
            //string sql = values[0].ToString();
            //string from = VAdvantage.DataBase.DB.ExecuteScalar(sql).ToString();

            string from = user.Email;

            string[] to = null;
            string[] bc = null;
            StringBuilder bcctext = new StringBuilder();
            StringBuilder totext = new StringBuilder();
            StringBuilder cctext = new StringBuilder();
            string[] cc = null;
            string sub = null;
            string message = null;

            VAdvantage.Utility.EMail sendmail = null;
            List<string> res1 = new List<string>();
            for (int j = 0; j < mails.Count; j++)
            {
                to = mails[j].To;
                bc = mails[j].Bcc;
                cc = mails[j].Cc;

                sub = mails[j].Subject;
                message = mails[j].Body;
                sendmail = new VAdvantage.Utility.EMail(ctx, smtphost, smtpport, issl, from, "", "", "", sub, message,
                true, user.Username, user.Password, user.SmtpAuthentication);

                if (to != null)
                {

                    for (int i = 0; i < to.Length; i++)
                    {
                        if (to[i].ToString() != "")
                        {
                            sendmail.AddTo(to[i].ToString(), "");
                            totext.Append(to[i].ToString() + ",");
                        }
                    }
                }

                if (bc != null)
                {
                    for (int i = 0; i < bc.Length; i++)
                    {
                        if (bc[i].ToString() != "")
                        {
                            sendmail.AddBcc(bc[i].ToString(), "");
                            bcctext.Append(bc[i].ToString() + ",");
                        }
                    }
                }

                if (cc != null)
                {
                    for (int i = 0; i < cc.Length; i++)
                    {
                        if (cc[i].ToString() != "")
                        {
                            sendmail.AddCc(cc[i].ToString(), "");
                            cctext.Append(cc[i].ToString() + ",");
                        }
                    }
                }

                res1.Add(sendmail.Send());
            }
            return res1;
        }
        public string DeleteFiles()
        {
            try
            {
                if (Directory.Exists(this.attachmentsDirectory))
                {
                    foreach (var file in Directory.GetFiles(this.attachmentsDirectory))
                    {
                        var creationTime = File.GetCreationTime(file);
                        if (DateTime.Now - creationTime > TimeSpan.FromHours(1))
                        {
                            File.Delete(file);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "True";

        }

        public bool SetProductQty(int recordID, string keyColName, List<int> product, List<decimal> qty, int lineID, IDictionary<string, string> ctxmap)
        {
            //int WindowNo = 0;
            //VAdvantage.Classes.Context ctx = new VAdvantage.Classes.Context(ctxmap);
            Env.SetContext(new VAdvantage.Classes.Context(ctxmap));
            //VAdvantage.Classes.Context ctx = new VAdvantage.Classes.Context(ctxmap);


            if (keyColName.ToUpper().Trim() == "C_ORDER_ID")
            {
                MOrder ord = new MOrder(Env.GetCtx(), recordID, null);
                for (int i = 0; i < product.Count; i++)
                {
                    MOrderLine oline = new MOrderLine(Env.GetCtx(), lineID, null);
                    oline.SetAD_Client_ID(ord.GetAD_Client_ID());
                    oline.SetAD_Org_ID(ord.GetAD_Org_ID());
                    oline.SetM_Product_ID(product[i]);
                    oline.SetQty(qty[i]);
                    oline.SetC_Order_ID(recordID);


                    //MProduct prd = MProduct.Get(Env.GetCtx(), product[i]);
                    //if (prd.IsStocked())
                    //{
                    //    int M_Warehouse_ID = Env.GetCtx().GetContextAsInt(WindowNo, "M_Warehouse_ID");
                    //    int M_AttributeSetInstance_ID = Env.GetCtx().GetContextAsInt(WindowNo, "M_AttributeSetInstance_ID");
                    //    Decimal? available = MStorage.GetQtyAvailable(M_Warehouse_ID, product[i], M_AttributeSetInstance_ID, null);
                    //    if (available == null)
                    //        available = Env.ZERO;
                    //    if (available == 0)
                    //    {
                    //        //mTab.fireDataStatusEEvent("NoQtyAvailable", "0", false);
                    //        // ShowMessage.Info("NoQtyAvailable", null, "0", "");
                    //    }
                    //    else if (available.Value.CompareTo(qty[i]) < 0)
                    //    {
                    //        // ShowMessage.Info("InsufficientQtyAvailable", null, available.ToString(), "");
                    //    }
                    //    else
                    //    {
                    //        int C_OrderLine_ID = oline.GetC_OrderLine_ID();
                    //        //if (mTab.GetValue("C_OrderLine_ID") == DBNull.Value)
                    //        //{
                    //        //    C_OrderLine_ID = 0;
                    //        //}
                    //        //else
                    //        //{
                    //        //    C_OrderLine_ID = System.Convert.ToInt32(mTab.GetValue("C_OrderLine_ID"));
                    //        //}
                    //        if (C_OrderLine_ID == null)
                    //            C_OrderLine_ID = 0;
                    //        Decimal notReserved = MOrderLine.GetNotReserved(Env.GetCtx(),
                    //            M_Warehouse_ID, product[i], M_AttributeSetInstance_ID,
                    //            C_OrderLine_ID);
                    //        if (notReserved == null)
                    //            notReserved = Env.ZERO;
                    //        Decimal total = Decimal.Subtract(available.Value, notReserved);
                    //        if (total.CompareTo(qty[i]) < 0)
                    //        {
                    //            String info = Msg.ParseTranslation(Env.GetCtx(), "@QtyAvailable@=" + available
                    //                + "  -  @QtyNotReserved@=" + notReserved + "  =  " + total);
                    //            //  ShowMessage.Info("InsufficientQtyAvailable", null, info, "");
                    //        }
                    //    }
                    //}



                    if (!oline.Save())
                    {

                    }
                }
            }
            else if (keyColName.ToUpper().Trim() == "C_INVOICE_ID")
            {
                MInvoice inv = new MInvoice(Env.GetCtx(), recordID, null);
                for (int i = 0; i < product.Count; i++)
                {
                    MInvoiceLine invline = new MInvoiceLine(Env.GetCtx(), lineID, null);
                    invline.SetAD_Client_ID(inv.GetAD_Client_ID());
                    invline.SetAD_Org_ID(inv.GetAD_Org_ID());
                    invline.SetM_Product_ID(product[i]);
                    invline.SetQty(qty[i]);
                    invline.SetC_Invoice_ID(recordID);
                    if (!invline.Save())
                    {

                    }
                }
            }
            else if (keyColName.ToUpper().Trim() == "M_INOUT_ID")
            {
                MInOut inv = new MInOut(Env.GetCtx(), recordID, null);
                for (int i = 0; i < product.Count; i++)
                {
                    MInOutLine ioline = new MInOutLine(Env.GetCtx(), lineID, null);
                    ioline.SetAD_Client_ID(inv.GetAD_Client_ID());
                    ioline.SetAD_Org_ID(inv.GetAD_Org_ID());
                    ioline.SetM_Product_ID(product[i]);
                    ioline.SetQty(qty[i]);
                    ioline.SetM_InOut_ID(recordID);
                    if (!ioline.Save())
                    {

                    }
                }
            }
            //else if (keyColName.ToUpper().Trim() == "M_MOVEMENT_ID")
            //{
            //    MMovement inv = new MMovement(Env.GetCtx(), recordID, null);
            //    for (int i = 0; i < product.Count; i++)
            //    {
            //        MMovementLine mline = new MMovementLine(Env.GetCtx(), lineID, null);
            //        mline.SetAD_Client_ID(inv.GetAD_Client_ID());
            //        mline.SetAD_Org_ID(inv.GetAD_Org_ID());
            //        mline.SetM_Product_ID(product[i]);
            //        mline.SetMovementQty(qty[i]);
            //        mline.SetM_Locator_ID(101);
            //        mline.SetM_Movement_ID(recordID);
            //        if (!mline.Save())
            //        {

            //        }
            //    }
            //}
            //else if (keyColName.ToUpper().Trim() == "M_INVENTORY_ID")
            //{
            //    MInventory inv = new MInventory(Env.GetCtx(), recordID, null);
            //    for (int i = 0; i < product.Count; i++)
            //    {
            //        MInventoryLine invline = new MInventoryLine(Env.GetCtx(), lineID, null);
            //        invline.SetAD_Client_ID(inv.GetAD_Client_ID());
            //        invline.SetAD_Org_ID(inv.GetAD_Org_ID());
            //        invline.SetM_Locator_ID(101);
            //        invline.SetM_Product_ID(product[i]);
            //        invline.SetQtyCount(qty[i]);
            //        invline.SetM_Inventory_ID(recordID);
            //        if (!invline.Save())
            //        {

            //        }
            //    }
            //}

            return true;
        }


        #region YouTube


        public ModelYTInfo GetStandardYouTubeFeed(string prmFeedIdentifier)
        {


            try
            {
                Feed<Video> innerFeeds = null;
                ModelYTInfo returnMain = null;

                //prepare request object for standard feed. no authentication required
                YouTubeRequest localRequest = InitializeRequest("", "");

                if (localRequest == null)
                {
                    return null;
                }

                //get the standard Feed by Identifier uri
                innerFeeds = localRequest.GetStandardFeed(prmFeedIdentifier);


                returnMain = new ModelYTInfo();

                //Get total results count
                returnMain.TotalResults = innerFeeds.TotalResults;

                //video entry collection
                returnMain.Entries = PrepareFeed(innerFeeds);

                //return feed
                return returnMain;

            }
            catch (Exception)
            {
                return null;
            }
        }


        private YouTubeRequest InitializeRequest(string prmUserName, string prmPassword)
        {
            try
            {
                //Reading Web.config for the Developer's Key
                var local_devkey_config = VAdvantageSvc.Classes.ServerEndPoint.GetDeveloperKey();

                if (String.IsNullOrEmpty(local_devkey_config.ToString()) == true)
                {
                    return null;
                }

                YouTubeRequestSettings tubeSettings;

                if (prmUserName.Trim().Length > 0 && prmPassword.Trim().Length > 0)
                {
                    //user supplied username and password
                    tubeSettings = new YouTubeRequestSettings("Advantage", local_devkey_config, prmUserName.Trim(), prmPassword.Trim());
                }
                else
                {
                    //intention to get public feed
                    tubeSettings = new YouTubeRequestSettings("Advantage", local_devkey_config);
                }


                //prepare the request object by passing the settings object
                YouTubeRequest myTubeRequest = new YouTubeRequest(tubeSettings);

                //return the prepared YouTubeRequest object
                return myTubeRequest;
            }
            catch (Exception)
            {
                return null;
            }

        }



        public ModelYTInfo GetYouTubeByKeyword(string prmKeyword,
                                                    Boolean prmSafeSearch,
                                                    string prmOrderBy,
                                                    string prmVideosBetweenTimeRange,
                                                    string prmVideoCategory,
                                                    int prmCurrentPage,
                                                    int prmPageSize)
        {
            try
            {
                Feed<Video> innerFeeds = null;
                ModelYTInfo returnMain = null;

                //prepare request object for standard feed. no authentication required
                YouTubeRequest localRequest = InitializeRequest("", "");

                if (localRequest == null)
                {
                    return null;
                }

                //YouTubeQuery object that specifies your search criteria
                YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

                //search result includes everything
                if (prmSafeSearch == false)
                {
                    query.SafeSearch = YouTubeQuery.SafeSearchValues.None;
                }


                if (String.IsNullOrEmpty(prmVideosBetweenTimeRange) != true)
                {
                    //sets a time period to limit standard feed results to 
                    //one of the members of the YouTubeQuery.UploadTime enumeration.
                    if (prmVideosBetweenTimeRange.Trim().ToLower() == "all")
                        query.Time = YouTubeQuery.UploadTime.AllTime;
                    else if (prmVideosBetweenTimeRange.Trim().ToLower() == "today")
                        query.Time = YouTubeQuery.UploadTime.Today;
                    else if (prmVideosBetweenTimeRange.Trim().ToLower() == "currentweek")
                        query.Time = YouTubeQuery.UploadTime.ThisWeek;
                    else if (prmVideosBetweenTimeRange.Trim().ToLower() == "currentmonth")
                        query.Time = YouTubeQuery.UploadTime.ThisMonth;
                }

                //sets the order in which to list entries, 
                //i.e. relevance, viewCount, published, or rating.
                if (String.IsNullOrEmpty(prmOrderBy) != true)
                {
                    query.OrderBy = prmOrderBy;
                }


                if (String.IsNullOrEmpty(prmVideoCategory) != true)
                {
                    //Searching for videos using categories
                    QueryCategory q = new QueryCategory(new AtomCategory(prmVideoCategory));
                    query.Categories.Add(q);
                }

                //paging implementation 
                //sets the 1-based index of the first result to be retrieved
                query.StartIndex = prmPageSize * prmCurrentPage;
                //sets the maximum number of entries to return at one time
                query.NumberToRetrieve = prmPageSize;

                //sets a search query term
                //searches for the specified string in all video metadata
                query.Query = prmKeyword.Trim();

                //returns a new feed based on the operation passed in. 
                innerFeeds = localRequest.Get<Video>(query);

                //Get total results count
                returnMain = new ModelYTInfo();

                //Get total results count
                returnMain.TotalResults = innerFeeds.TotalResults;

                //video entry collection
                returnMain.Entries = PrepareFeed(innerFeeds);

                //return feed
                return returnMain;
            }
            catch (Exception)
            {

                return null;
            }
        }


        public ModelYTInfo GetPrivateFeed(int sIndex, int pSize, string orderby
                                           , string lang, string search, string videoRange)
        {

            Feed<Video> innerFeeds = null;
            ModelYTInfo returnMain = null;
            YouTubeRequest localRequest = null;

            try
            {
                string ytUser = VAdvantageSvc.Classes.ServerEndPoint.GetYTUser();


                //prepare request object for standard feed. no authentication required
                localRequest = InitializeRequest("", "");
                //YouTubeQuery object that specifies your search criteria
                YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);


                if (String.IsNullOrEmpty(videoRange) != true)
                {
                    //sets a time period to limit standard feed results to 
                    //one of the members of the YouTubeQuery.UploadTime enumeration.
                    if (videoRange.Trim().ToLower() == "all")
                        query.Time = YouTubeQuery.UploadTime.AllTime;
                    else if (videoRange.Trim().ToLower() == "today")
                        query.Time = YouTubeQuery.UploadTime.Today;
                    else if (videoRange.Trim().ToLower() == "currentweek")
                        query.Time = YouTubeQuery.UploadTime.ThisWeek;
                    else if (videoRange.Trim().ToLower() == "currentmonth")
                        query.Time = YouTubeQuery.UploadTime.ThisMonth;
                }

                //sets the order in which to list entries, 
                //i.e. relevance, viewCount, published, or rating.
                if (String.IsNullOrEmpty(orderby) != true)
                {
                    query.OrderBy = orderby;
                }

                //paging implementation 
                //sets the 1-based index of the first result to be retrieved
                query.StartIndex = sIndex;
                //sets the maximum number of entries to return at one time
                query.NumberToRetrieve = pSize;

                //sets a search query term
                //searches for the specified string in all video metadata
                if (!string.IsNullOrEmpty(search))
                {
                    query.Query = search;
                }

                query.LR = lang;
                query.Author = ytUser;
                //returns a new feed based on the operation passed in. 
                innerFeeds = localRequest.Get<Video>(query);


                ////prepare request object for private feed using valid username and password
                //localRequest = InitializeRequest(ytUser,"");


                //if (localRequest == null)
                //{
                //    return null;
                //}

                ////if the user provides email as a username, extract the username
                ////if its not a email address, then pass the username as it is.
                //string[] localUserName = ytUser.Split('@');
                //ytUser = localUserName[0];

                ////build the uri string that includes the username
                //string localUri
                //    = ("http://gdata.youtube.com/feeds/api/users/###user###/uploads?start-index=" + sIndex + "&max-results=" + pSize +"&).Replace("###user###", ytUser.Trim());

                ////Now build the Uri object
                //Uri uri = new Uri(localUri);




                ////returns a new feed based on the Uri.
                //innerFeeds = localRequest.Get<Video>(uri);
                //return feed

                // }
                //Get total results count
                returnMain = new ModelYTInfo();

                //Get total results count
                returnMain.TotalResults = innerFeeds.TotalResults;

                //video entry collection
                returnMain.Entries = PrepareFeed(innerFeeds);
                return returnMain;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static List<ModelYTEntryInfo> PrepareFeed(Feed<Video> innerFeeds)
        {
            try
            {
                List<ModelYTEntryInfo> localFeeds = new List<ModelYTEntryInfo>();

                foreach (Video itemEntry in innerFeeds.Entries)
                {
                    ModelYTEntryInfo localEnt = new ModelYTEntryInfo();
                    localEnt.ID = itemEntry.Id;
                    localEnt.VideoID = itemEntry.VideoId.Trim();
                    localEnt.Title = itemEntry.Title;
                    localEnt.UploadedBy = itemEntry.Uploader;
                    localEnt.Description = itemEntry.Description;
                    localEnt.ViewCount = itemEntry.ViewCount;

                    localEnt.RatingAverage = Math.Round(itemEntry.RatingAverage, 1);


                    //All the Thumbnails images for the video
                    if (itemEntry.Thumbnails.Count > 0)
                    {

                        localEnt.ThumbnailImage = "";
                        foreach (MediaThumbnail thumbnail in itemEntry.Thumbnails)
                        {
                            //Taking only one thumbnail image in our case
                            if (thumbnail.Width == "120")
                            {
                                localEnt.ThumbnailImage = thumbnail.Url.Trim();
                            }
                            else if (thumbnail.Width != "120")
                            {
                                localEnt.Image = thumbnail.Url.Trim();
                            }

                        }
                        if (ServerEndPoint.IsSSLEnabled())
                        {
                            if (!String.IsNullOrEmpty(localEnt.ThumbnailImage))
                            {
                                localEnt.ThumbnailImage = localEnt.ThumbnailImage.Replace("http://", "https://");
                            }
                            if (!String.IsNullOrEmpty(localEnt.Image))
                            {
                                localEnt.Image = localEnt.Image.Replace("http://", "https://");
                            }
                        }
                    }


                    //Media content
                    if (itemEntry.Contents.Count > 0)
                    {
                        localEnt.Content = new List<ModelYTMediaContent>();

                        foreach (Google.GData.YouTube.MediaContent content in itemEntry.Contents)
                        {
                            localEnt.Content.Add(new ModelYTMediaContent
                            {
                                Url = content.Url,
                                Duration = content.Duration,
                                Type = content.Type
                            });
                        }
                    }


                    localFeeds.Add(localEnt);
                }
                return localFeeds;
            }
            catch (Exception)
            {

                return null;
            }

        }

        #endregion






        //public string GetConvertedCurrencyValue(CurrencyConverter.Currency from, CurrencyConverter.Currency to, string url)
        //{
        //    return  CurrencyConversion.GetConvertedCurrencyValue(from, to, url);
        //}

        //public string GetConvertedCurrencyValueM1(string from, string to, string url)
        //{
        //    return CurrencyConversion.GetConvertedCurrencyValue(from, to, url);
        //}
    }
    [DataContract]
    public class TenantInfo
    {
        [DataMember]
        public string TenantName
        {
            get;
            set;
        }
        [DataMember]
        public string OrgName
        {
            get;
            set;
        }
        [DataMember]
        public string AdminRole
        {
            get;
            set;
        }

        [DataMember]
        public string UserRole
        {
            get;
            set;
        }

        [DataMember]
        public string AdminUser
        {
            get;
            set;
        }

        [DataMember]
        public string AdminUserPwd
        {
            get;
            set;
        }

        [DataMember]
        public string OrgUser
        {
            get;
            set;
        }

        [DataMember]
        public string OrgUserPwd
        {
            get;
            set;
        }
        [DataMember]
        public string Log
        {
            get;
            set;
        }
    }

}
